'use strict';
const jwt = require('jsonwebtoken');
const {
  CommonUserTypeEnum,
  CommonStatusEnum
} = require('../utils/enum');
/**
 * 登录信息验证中间件
 */
module.exports = () => async (ctx, next) => {
  // 判断请求头中是否有 token
  const token_full = ctx.request.headers['authorization'] || '';
  // 去除Bearer前缀
  const token = token_full.replace('Bearer ', '');
  if (!token) {
    ctx.error(403);
    return;
  }
  try {
    const user = await jwt.verify(token, ctx.app.config.keys);
    const prefixMap = {
      [CommonUserTypeEnum.SYSTEM_USER]: 'systemUser',
      [CommonUserTypeEnum.USER]: 'user',
      [CommonUserTypeEnum.SHOP_USER]: 'ticketShop',
    }
    console.log('user-----',user)
    let res = null
    if (user.type === CommonUserTypeEnum.SYSTEM_USER) {
      res = await ctx.service.system.systemUser.findById(user.id);
    } else if (user.type === CommonUserTypeEnum.USER) {
      res = await ctx.service.business.user.findById(user.id);
    } else if (user.type === CommonUserTypeEnum.SHOP_USER) {
      res = await ctx.service.business.ticketShop.findById(user.id);
    }
    if (!res) {
      ctx.error(500, '用户不存在');
      return;
    } else {
      if (res.status !== CommonStatusEnum.ENABLE) {
        ctx.error(500, '用户已禁用');
      }
      ctx.user = {
        ...res.dataValues,
        type: user.type
      }
    }
    await next();
  } catch (e) {
    ctx.error(500, e.message);
  }
};
